package cn.leida.ruoyi.client.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.leida.base.git.config.AppGitCfg;
import cn.leida.ruoyi.client.service.ISysClientService;
import cn.leida.ruoyi.client.types.ClientDataType;
import cn.leida.ruoyi.client.util.ClientDataUtil;
import cn.leida.ruoyi.client.util.ClientMenuUtil;
import cn.leida.ruoyi.common.core.domain.entity.SysMenu;
import cn.leida.ruoyi.common.core.domain.entity.SysRole;
import cn.leida.ruoyi.system.dao.SysRoleDao;
import cn.leida.ruoyi.system.service.ISysMenuService;
import cn.leida.ruoyi.system.util.SysMenuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;


/**
 * 参数配置 服务层实现
 *
 * @author liutietou
 * @since 1.0  2020-12-11
 */
@Service
public class SysClientServiceImpl implements ISysClientService {
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private SysRoleDao roleDao;

    @Override
    public void saveClientData() {
        // 角色菜单
        saveClientMenu();
    }

    private void saveClientMenu() {
        List<SysRole> roleList = roleDao.findAll();
        if (CollectionUtil.isNotEmpty(roleList)) {
            for (SysRole role : roleList) {
                // 忽略超级管理员角色
                if (role.isAdmin()) {
                    // 所有菜单
                    List<SysMenu> menus = menuService.selectMenuList(new SysMenu());
                    File jsonFile = AppGitCfg.clientMenuJsonFile();
                    ClientMenuUtil.saveJsonFile(menus, jsonFile);
                } else {
                    // 查询角色的所有菜单
                    List<SysMenu> menus = menuService.findRoleMenuList(role.getRoleId());
                    File jsonFile = AppGitCfg.roleKeyJsonFile(role.getRoleKey());
                    ClientMenuUtil.saveJsonFile(menus, jsonFile);
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void loadClientData() {
        // 角色菜单
        loadClientMenu();
    }
    @Transactional(rollbackFor = Exception.class)
    private void loadClientMenu() {
        // 不需要更新
        if (!ClientDataUtil.needUpdate(ClientDataType.menu)) {
            return;
        }
        menuService.deleteByMinMenuId(0L);
        List<SysMenu> menus = ClientMenuUtil.loadSysMenuList();
        // 转换树形结构
        List<SysMenu> treeMenus = SysMenuUtil.buildMenuTree(menus);
        for (SysMenu topMenu : treeMenus) {
            if (topMenu.topMenu()) {
                menuService.saveChildren(topMenu);
            }
        }
        // 保存更新时间
        ClientDataUtil.saveUpdateTime(ClientDataType.menu);
    }

}
